package com.zaoniao.enstudy.infrastructure.persistence;

import com.zaoniao.enstudy.domain.entity.User;
import com.zaoniao.enstudy.domain.repository.UserRepository;
import com.zaoniao.enstudy.infrastructure.convert.UserCrt;
import com.zaoniao.enstudy.infrastructure.mapper.UserMapper;
import com.zaoniao.enstudy.infrastructure.po.UserPo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

/**
 * 用户仓储层业务实现类.
 * @author llb666
 */
@Repository
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserRepositoryImpl implements UserRepository {

    private final UserMapper userMapper;
    /**
     * 根据openId查询用户信息.
     *
     * @param openId 用户唯一标识
     * @return 用户信息
     */
    @Override
    public User getUserByOpenId(String openId) {
        Example example = new Example(UserPo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openId", openId);
        return UserCrt.INSTANCE.po2do(userMapper.selectOneByExample(example));
    }

    /**
     * 保存用户信息.
     *
     * @param user 用户信息
     * @return true / false
     */
    @Override
    public boolean saveUser(User user) {
        int insertCount = userMapper.insertUseGeneratedKeys(UserCrt.INSTANCE.do2po(user));
        return insertCount > 0;
    }

    /**
     * 修改用户信息.
     *
     * @param user 用户信息
     * @return true / false
     */
    @Override
    public boolean updateUser(User user) {
        // 根据openId修改用户信息.
        Example example = new Example(UserPo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openId", user.getOpenId());

        int updateCount = userMapper.updateByExampleSelective(UserCrt.INSTANCE.do2po(user), example);
        return updateCount > 0;
    }
}
